package com.example.service.user.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.config.ProjectProperties;
import com.example.exception.InsertException;
import com.example.exception.user.UserNotFoundException;
import com.example.exception.user.UnavailableUsernameException;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.user.UserLoginRegisterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author Lexin Huang, Yu Wang
 */
@Service
public class UserLoginRegisterServiceImpl extends ServiceImpl<UserMapper, User> implements UserLoginRegisterService {

    private final String DEFAULT_USER_AVATAR_URL;

    private final String DEFAULT_USER_INTRODUCTION;

    protected UserLoginRegisterServiceImpl(ProjectProperties projectProperties) {
        this.DEFAULT_USER_AVATAR_URL = projectProperties.getUserInfo().getAvatar().getDefaultAvatarUrl();
        this.DEFAULT_USER_INTRODUCTION = projectProperties.getUserInfo().getProfile().getDefaultIntroduction();
    }

    @Override
    public User normalLogin(String username, String password) {
        User user = baseMapper.getLoginUser(username, password);
        if (Objects.isNull(user)) {
            throw new UserNotFoundException("提供的用户名密码组合查询不到用户!");
        }
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public User register(String username, String password, String emailAddress) {
        checkIfNameIsAvailable(username);
        User user = createUserToRegister(username, password, emailAddress);
        if (!save(user)) {
            throw new InsertException("当前注册人数过多, 请重试!");
        }
        return user;
    }

    private void checkIfNameIsAvailable(String username) {
        if (null != baseMapper.getByUsername(username)) {
            throw new UnavailableUsernameException("用户名称为 " + username + " 的用户已存在!");
        }
    }

    /**
     * 用于创建注册时, 用于插入表的 User 对象
     * @param username     注册的用户名
     * @param password     密码
     * @param emailAddress 邮箱
     * @return User 对象, 参见{@link User}
     */
    public User createUserToRegister(String username, String password, String emailAddress) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmailAddress(emailAddress);
        user.setIntroduction(DEFAULT_USER_INTRODUCTION);
        user.setPortraitPath(DEFAULT_USER_AVATAR_URL);
        return user;
    }

}
